<!-- 发送验证码 -->
<template>
	<text :style="{color: color, fontSize: size, ...styleClass}" @tap="onSend">{{ timeFun ? timer + 's后重新获取' : startText }}</text>
</template>

<script setup>
	import { reactive, defineProps, defineEmits, ref } from 'vue'
	import { valiteMobile } from '@/utils/format'
	import { onSendCode } from '@/api/common.js'
	
	const emits = defineEmits(['onSend'])
	
	const props = defineProps({
		seconds: {
			type: Number,
			default: 60
		},
		startText: {
			type: String,
			default: '获取验证码'
		},
		endText: {
			type: String,
			default: '重新获取'
		},
		color: {
			type: String,
			default: '#5F85FF'
		},
		size: {
			type: String,
			default: '28rpx'
		},
		styleClass: {
			type: String,
			default: () => {}
		},
		value: {
			type: String,
			default: ''
		},
		type: {
			type: Number,
			default: 1
		},
		// 是否自定义判断事件
		isFun: {
			type: Boolean,
			deafult: false
		}
	})
	
	const timer = ref(60)
	const timeFun = ref(null)
	
	// 发送验证码
	const onSend = async () => {
		if (props.isFun && !valiteMobile(props.value)) return emits('onSend')
			
		if (props.value === '') return uni.showToast({
			duration: 3000,
			title: '手机号不能为空',
			icon: 'error'
		})
			
		if (!valiteMobile(props.value)) return uni.showToast({
			duration: 3000,
			title: '手机号格式错误，请重新输入',
			icon: 'error'
		})
		
		if (timeFun.value) return
		
		Promise.try(async () => {
			return onSendCode({itype: props.type, phoneNumber: props.value})
		}).then(res => {
			uni.showToast({
				title: '发送成功',
				duration: 3000,
				icon: 'success'
			})
		})
		
		timeFun.value = setInterval(() => {
			if (timer.value > 0) {
				timer.value--;
			} else {
				clearInterval(timeFun.value)
				timeFun.value = null;
				timer.value = 60
			}
		}, 1000)
	}
</script>

<style scoped lang="scss">

</style>